package com.centit.framework.ip.oa.controller;

import com.alibaba.fastjson.JSONObject;
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.ip.businessdata.po.InterfaceLog;
import com.centit.framework.ip.businessdata.service.InterfaceLogManager;
import com.centit.framework.ip.oa.po.UserBind;
import com.centit.framework.ip.util.Des3;
import com.centit.framework.model.basedata.IUserInfo;
import com.centit.framework.security.model.CentitPasswordEncoder;
import com.centit.framework.security.model.CentitUserDetails;
import com.centit.framework.system.po.UserInfo;
import com.centit.framework.system.service.SysUserManager;
import com.centit.support.algorithm.UuidOpt;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
import java.security.MessageDigest;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.centit.framework.ip.oa.service.UserBindManager;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.centit.framework.core.controller.BaseController;

/**
 * UserBind  Controller.
 * create by scaffold 2018-10-09 
 * @author ydz
 * 用户绑定表用户绑定表，用于与投管系统的用户绑定   
*/


@Controller
@RequestMapping("/oa/userbind")
public class UserBindController  extends BaseController {
	private static final Log log = LogFactory.getLog(UserBindController.class);
	
	@Resource
	private UserBindManager userBindMag;
	@Resource
    private SysUserManager sysUserManager;
    @Resource
    private CentitPasswordEncoder passwordEncoder;
    @Resource
    protected InterfaceLogManager interfaceLogMag;

    /**
     * 从投管跳转执行方法，判断是否绑定，如果绑定，找到对应绑定的OA用户，更新用户表token，跳转登录
     * 如果未绑定，跳转至绑定页面
     * @param response
     * @param request
     */
    @RequestMapping(value="/checkUser",method = {RequestMethod.GET})
    public void checkUser(HttpServletResponse response, HttpServletRequest request){
        String tzUserId = request.getParameter("USERID");//投管系统的userId
        String itemId = request.getParameter("ITEMID");//事项ID
        String sendId = request.getParameter("SENDID");//事项办理流水号
        String dealCode = request.getParameter("DEAL_CODE");//项目编码
        UserBind userBind = userBindMag.getUserByTzUserId(tzUserId);
        if(userBind!=null){
            String tkStr = tzUserId+System.currentTimeMillis();
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] result = md.digest(tkStr.getBytes());
                StringBuffer token = new StringBuffer();
                for (byte b : result) {
                    int number = b & 0xff;
                    String str = Integer.toHexString(number);
                    if (str.length() == 1) {
                        token.append("0");
                    }
                    token.append(str);
                }
                if(StringUtils.isNotBlank(token.toString())){
                    //将token更新至对应的OA用户表中
                    userBindMag.updateTokenToUser(userBind.getUserCode(),token.toString());
                }
                IUserInfo userInfo = CodeRepositoryUtil.getUserInfoByCode(userBind.getUserCode());
                String casHome = CodeRepositoryUtil.getSysConfigValue("login.cas.casHome");
                String ipHome = CodeRepositoryUtil.getSysConfigValue("login.cas.localHome");
                String url = casHome+"/login?service="+ipHome+"/login/cas&username="+userInfo.getLoginName()
                        +"&tgticket="+token;
                //TODO，此处需添加跳转页面的方法

            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            //TODO，此处需添加跳转至绑定页面的方法
        }
    }

    /**
     * 投管平台与OA平台的绑定方法
     * @param response
     * @param request
     */
    @RequestMapping(value="/saveBind",method = {RequestMethod.GET})
    public void saveBind(HttpServletResponse response, HttpServletRequest request){
        CentitUserDetails cud = getLoginUser(request);
        String tzUserId = request.getParameter("tzUserId");//投管系统的userId
        String userCode = request.getParameter("userCode");//对应OA的用户
        if(StringUtils.isNotBlank(tzUserId)){
            UserBind userBind = userBindMag.getUserByTzUserId(tzUserId);

            if(userBind!=null && userCode.equals(userBind.getUserCode())){
                UserBind ub = new UserBind();
                ub.copyNotNullProperty(userBind);
                if(!"T".equals(ub.getIsvalid())){
                    ub.setIsvalid("T");
                    ub.setLastUpdateTime(new Date());
                    if(cud!=null){
                        ub.setLastUpdateUserCode(cud.getUserCode());
                    }
                    userBindMag.mergeObject(ub);
                }
            }else{
                String recId = UuidOpt.getUuidAsString32();
                userBind = new UserBind();
                userBind.setRecId(recId);
                userBind.setTzUserid(tzUserId);
                userBind.setUserCode(userCode);
                userBind.setCreateTime(new Date());
                if(cud!=null){
                    userBind.setLastUpdateUserCode(cud.getUserCode());
                }
                userBind.setLastUpdateTime(new Date());
                userBindMag.saveNewObject(userBind);
            }
        }
    }

    /**
     * 投管平台与OA平台的解除绑定方法
     * @param response
     * @param request
     */
    @RequestMapping(value="/removeBind",method = {RequestMethod.GET})
    public void removeBind(HttpServletResponse response, HttpServletRequest request){
        CentitUserDetails cud = getLoginUser(request);
        String userCode = request.getParameter("userCode");//对应OA的用户
        if(StringUtils.isNotBlank(userCode)){
            UserBind userBind = userBindMag.getUserByUserCode(userCode);
            if(userBind!=null){
                userBind.setIsvalid("F");
                userBind.setLastUpdateTime(new Date());
                if(cud!=null){
                    userBind.setLastUpdateUserCode(cud.getUserCode());
                }
                userBindMag.mergeObject(userBind);
            }
        }
    }

    /**
     * 功能描述: 用户名密码登录
     *
     * @param:验证用户名密码是否匹配
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-6-28 13:31
     */
    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    public void checkLogin(HttpServletResponse response, HttpServletRequest request) {
        String loginName = request.getParameter("loginName");
        String pwd = request.getParameter("pwd");
        JSONObject result = new JSONObject();
        try {
            pwd = Des3.decode(pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserInfo userInfo = sysUserManager.loadUserByLoginname(loginName);
        String code = "0";
        String desc = "绑定成功";
        if (userInfo != null) {
            Boolean enBool = passwordEncoder.isPasswordValid(userInfo.getUserPin(),
                    pwd, userInfo.getUserCode());
            if (enBool) {
                try {

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                code = "1";
                desc = "用户密码不正确";
            }
        } else {
            code = "1";
            desc = "用户登录名不存在";
        }
        result.put("code",code);
        result.put("desc",desc);

        //记录调用日志
        InterfaceLog interfaceLog = new InterfaceLog();
        interfaceLog.setRecordid(UuidOpt.getUuidAsString());
        interfaceLog.setCreater(getLoginUserCode(request));
        interfaceLog.setCreateTime(new Date());
        interfaceLog.setMethodflag("bindUser");
        interfaceLog.setSystemflag("bindUserKey");
        interfaceLog.setResponse("code:" + code + ";desc:" + desc);
        interfaceLog.setYwflag("0");
        interfaceLog.setResultflag("T");
        this.interfaceLogMag.saveNewObject(interfaceLog);

        JsonResultUtils.writeSingleDataJson(result,response);
    }
}
